package android.slc.box.core.ui;

import android.slc.box.core.notification.NotificationObserver;
import android.slc.box.rxlifecycle.SimpleLifecycleScopeProvider;
import autodispose2.AutoDispose;
import autodispose2.AutoDisposeConverter;

import java.util.HashSet;
import java.util.Set;

public class VmBox {

    private ProtectedViewModelImpl protectedViewModel;
    private final Set<NotificationObserver> publishXNotificationObserver = new HashSet<>();

    protected SimpleLifecycleScopeProvider lifecycleScopeProvider;
    protected boolean canStopLifecycleScope = false;


    /**
     * 设置 RxLifecycleDelegate
     *
     * @param lifecycleScopeProvider
     */
    public void setRxLifecycleScopeProvider(SimpleLifecycleScopeProvider lifecycleScopeProvider) {
        this.lifecycleScopeProvider = lifecycleScopeProvider;
    }

    /**
     * 绑定生命周期
     *
     * @param <T>
     * @return
     */
    public <T> AutoDisposeConverter<T> bindToLifecycle() {
        return AutoDispose.autoDisposable(lifecycleScopeProvider);
    }

    public final void registerLiveEventFromVm(ProtectedViewModelImpl protectedViewModel) {
        if (this.protectedViewModel != null) {
            return;
        }
        this.protectedViewModel = protectedViewModel;
    }

    public void publish(String messageName, Object... payload) {
        if (protectedViewModel == null) {
            throw new NullPointerException("publishX为空，请注册本VmBox");
        }
        protectedViewModel.publish(messageName, payload);
    }

    public void subscribe(String messageName, NotificationObserver observer) {
        if (protectedViewModel == null) {
            throw new NullPointerException("publishX为空，请注册本VmBox");
        }
        publishXNotificationObserver.add(observer);
        protectedViewModel.subscribe(messageName, observer);
    }

    final void clear() {
        onCleared();
    }

    protected void onCleared() {
        publishXNotificationObserver.forEach(notificationObserver -> {
            if (notificationObserver != null) {
                protectedViewModel.unsubscribe(notificationObserver);
            }
        });
        this.protectedViewModel = null;
        if (canStopLifecycleScope) {
            lifecycleScopeProvider.stop();
        }
    }

}
